const jwt = require('jsonwebtoken');

module.exports = () => {
    return async (ctx,next) => {
        //1.排除不需要校验token的接口  
        let writeArr = ['/api/login','/api/registry'];
        if(writeArr.includes(ctx.request.url)){
            await next();   
        }else{
            //2.获取token
            let token = ctx.get('token');

            try{
                let obj = jwt.verify(token,'lixd');
                console.log(obj);
                ctx.request.role_id = obj.role_id;
                await next();
            }catch(e){
                if(e.name === 'TokenExpiredError' || e.name === 'JsonWebTokenError'){
                    ctx.status = 401;
                    ctx.body = {
                        code:4,
                        msg:'鉴权失败'
                    }
                }else{
                    ctx.body = {
                        code:5,
                        msg:e
                    }
                }
            }
        }
    }
}